package com.wuxiaolong.backend.interceptor;

import com.alibaba.fastjson.JSON;
import com.wuxiaolong.backend.constant.BusinessException;
import com.wuxiaolong.backend.constant.ResultCode;
import com.wuxiaolong.backend.model.JsonResult;
import com.wuxiaolong.backend.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Description: 拦截器对请求进行拦截 校验token
 *
 * @author Leo
 * @date 2020-04-19
 */

@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(request.getMethod().equals("OPTIONS")){
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        response.setCharacterEncoding("utf-8");
        String token = request.getHeader("authorization");
        if(token != null){
            boolean result = TokenUtil.verify(token);
            if(result){
                log.debug("token验证成功，通过拦截器");
                return true;
            }
        }
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        // 解决响应时的跨域问题，这里需要单独设置，因为不会走到下面afterCompletion
        response.setHeader("Access-Control-Allow-Origin", "*");

        JsonResult jr = new JsonResult(ResultCode.TOKEN_INVOILD_ERR.getCode(),ResultCode.TOKEN_INVOILD_ERR.getMsg());
        response.getWriter().append(JSON.toJSONString(jr));
        log.error("token认证失败，未通过拦截器");
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        response.setHeader("Access-Control-Allow-Credentials", "true");
//        response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type, X-Requested-With, token");
//        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS, POST, PUT, DELETE");
//        response.setHeader("Access-Control-Allow-Origin", "*");
//        response.setHeader("Access-Control-Max-Age", "3600");
//        vary: Origin
//        Vary: Access-Control-Request-Method
//        Vary: Access-Control-Request-Headers
//        Access-Control-Allow-Origin: *
    }
}
